<template>
  <div>
    <div class="pending">
      <!-- 搜索 -->
      <div class="formSearch">
        <el-form :inline="true" :model="searchData">
          <el-form-item label="店铺名称">
            <el-input v-model="searchData.shopName" maxlength="20" placeholder="请输入店铺名称" />
          </el-form-item>
          <el-form-item label="店铺编码">
            <el-input v-model="searchData.shopCode" maxlength="20" placeholder="请输入店铺编码" />
          </el-form-item>
          <el-form-item label="负责人">
            <el-input v-model="searchData.chargePersonName" maxlength="20" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="合同状态">
            <el-select v-model="searchData.contractState" placeholder="请选择">
              <el-option label="有效" value="1" />
              <el-option label="无效" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="search">查询 </el-button>
            <el-button type="success" plain @click="addbuss">新建商家</el-button>
            <el-button type="primary" plain @click="handleUrl">更换域名</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#EEF3FF', color: '#333333', width: '150px' }"
        tooltip-effect="dark"
        :style="{ width: '100%' }"
        class="dataTable"
        scrollbar-always-on
      >
        <el-table-column label="ID" prop="shopId" min-width="70" />
        <el-table-column label="店铺名称" min-width="140">
          <template #default="scope">{{ scope.row.shopName }}</template>
        </el-table-column>
        <el-table-column prop="shopCode" label="店铺编码" min-width="140" />
        <el-table-column prop="chargePersonName" label="负责人" min-width="100" show-overflow-tooltip />
        <el-table-column prop="chargePersonPhone" label="联系电话" min-width="120" />
        <el-table-column label="合同状态" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.contractState === 0">无效</span>
            <span v-if="scope.row.contractState === 1">有效</span>
          </template>
        </el-table-column>
        <el-table-column prop="bandwidth" label="流量余额" min-width="100">
          <template #default="scope">
            <el-text :type="scope.row.bandwidth * -1 > scope.row.bandwidthLimit ? 'danger' : ''">{{
              scope.row.bandwidth + ' GB'
            }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="trafficUnitPrice" label="流量单价" min-width="100">
          <template #default="scope">{{
            scope.row.trafficUnitPrice ? scope.row.trafficUnitPrice + ' 元/GB' : ''
          }}</template>
        </el-table-column>
        <el-table-column prop="bandwidthLimit" label="流量阈值" min-width="100">
          <template #default="scope">{{ scope.row.bandwidthLimit ? scope.row.bandwidthLimit + ' GB' : '' }}</template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="120" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="btnList">
              <el-button link type="primary" @click="seeMore(scope.row)">查看</el-button>
              <el-button link type="primary" @click="edit(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.state == 1" link type="primary" @click="disableOrEnable(scope.row)"
                >禁用</el-button
              >
              <el-button v-else link type="primary" @click="disableOrEnable(scope.row)">启用</el-button>
              <el-button link type="primary" @click="openDomain(scope.row)">查看域名</el-button>
              <el-popconfirm title="确认删除？" @confirm="delBusiness(scope.row)">
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
              <el-button link type="primary" @click="openDialogRecharge(scope.row)">充值</el-button>
              <el-button link type="primary" @click="openDialogRechargeLog(scope.row)">流量记录</el-button>
              <el-button link type="primary" @click="flushed(scope.row)">刷新经销商域名</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="searchData.page"
        :page-size="searchData.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        :total="total"
        style="margin: 12px 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- ******************************************************弹框开始****************************************************** -->
      <!-- 详情 -->
      <el-dialog v-model="detailsVisible" :align-center="true" title="查看商家" width="800" center>
        <div>
          <el-descriptions v-loading="detailLoading" :column="2">
            <el-descriptions-item width="50%" label="账号">{{ formData.shopPhone }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="店铺名称">{{ formData.shopName }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="店铺负责人">{{ formData.chargePersonName }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="负责人电话">{{
              hidden(formData.chargePersonPhone, 3, 4)
            }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="店铺地址">{{ formData.shopAdress }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="生效日期">{{
              formData.effectiveDate ? moment(formData.effectiveDate).format('YYYY-MM-DD') : '无'
            }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="失效日期">{{
              formData.expirationDate ? moment(formData.expirationDate).format('YYYY-MM-DD') : '无'
            }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="合同状态">{{
              formData.contractState ? '有效' : '无效'
            }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="直播间审核">{{
              formData.auditLive ? '开启' : '关闭'
            }}</el-descriptions-item>
            <el-descriptions-item width="50%" label="直播间商品审核">{{
              formData.auditLiveProduct ? '开启' : '关闭'
            }}</el-descriptions-item>
          </el-descriptions>
          <el-divider style="margin-top: 8px" />
          <el-descriptions v-loading="detailLoading" :column="2">
            <div v-for="(group, i) in shopConfigList" :key="i" class="config-panel">
              <!-- <div class="config-title">{{ group[0].configTypeDescribe }}</div> -->
              <el-descriptions-item
                v-for="item in group"
                :key="item.shopId + '-' + item.configModelId"
                class="config-item"
                :label="item.configText"
                width="50%"
              >
                {{ item.configValue }}
              </el-descriptions-item>
            </div>
          </el-descriptions>
          <!-- <el-divider /> -->
        </div>
      </el-dialog>
      <!-- 新建\编辑商家弹框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="userState ? '修改商家' : '新增商家'"
        width="600"
        center
        top="50px"
        :close-on-click-modal="false"
        style="max-height: 90vh"
        @closed="onClosed"
      >
        <div style="overflow-y: auto; max-height: calc(90vh - 180px)">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" label-position="left">
            <el-tabs v-model="activeName">
              <el-tab-pane label="授权信息" name="first">
                <el-form-item label="店铺名称" prop="shopName">
                  <el-input v-model="formData.shopName" maxlength="20" placeholder="20个字符以内" />
                </el-form-item>
                <el-form-item label="店铺负责人" prop="chargePersonName">
                  <el-input v-model="formData.chargePersonName" maxlength="20" placeholder="20个字符以内" />
                </el-form-item>
                <el-form-item label="负责人电话" prop="chargePersonPhone">
                  <el-input
                    v-if="cpPhoneShow"
                    :model-value="hidden(formData.chargePersonPhone, 3, 4)"
                    maxlength="11"
                    placeholder="请输入手机号"
                  />
                  <!-- @focus="focuscpPhoneInput" -->
                  <el-input
                    v-else
                    ref="phoneRef"
                    v-model="formData.chargePersonPhone"
                    maxlength="11"
                    clearable
                    placeholder="请输入手机号"
                  />
                </el-form-item>
                <el-form-item label="店铺地址" prop="shopAdress">
                  <el-input v-model="formData.shopAdress" maxlength="60" placeholder="请输入店铺地址" />
                </el-form-item>
                <el-form-item label="店铺域名" prop="doMain">
                  <el-input v-model="formData.doMain" placeholder="请输入店铺域名" />
                </el-form-item>
                <el-form-item label="生效日期" prop="effectiveDate">
                  <el-date-picker
                    v-model="formData.effectiveDate"
                    :disabled-date="disabledDate"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="选择日期"
                    autocomplete="effectiveDate"
                  />
                </el-form-item>
                <el-form-item label="失效日期" prop="expirationDate">
                  <el-date-picker
                    v-model="formData.expirationDate"
                    :disabled-date="disabledDateEnd"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    type="date"
                    placeholder="选择日期"
                    autocomplete="expirationDate"
                  />
                </el-form-item>
                <el-form-item label="合同状态" prop="contractState">
                  <el-radio-group v-model="formData.contractState">
                    <el-radio :value="1">有效 </el-radio>
                    <el-radio :value="0">无效 </el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="直播间审核" prop="auditLive">
                  <el-radio-group v-model="formData.auditLive">
                    <el-radio :value="1">开启 </el-radio>
                    <el-radio :value="0">关闭 </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="直播间商品审核" prop="auditLiveProduct">
                  <el-radio-group v-model="formData.auditLiveProduct">
                    <el-radio :value="1">开启 </el-radio>
                    <el-radio :value="0">关闭 </el-radio>
                  </el-radio-group>
                </el-form-item> -->
              </el-tab-pane>
              <el-tab-pane label="客户信息" name="second">
                <el-form-item label="账号" prop="shopPhone">
                  <!-- v-if="shopPhoneShow" -->
                  <el-input
                    v-model="formData.shopPhone"
                    autocomplete="shopPhone"
                    maxlength="20"
                    placeholder="请输入账号"
                    readonly
                    @focus="focusShopPhoneInput"
                  />
                  <!-- <el-input
                    v-else
                    ref="accountRef"
                    v-model="formData.shopPhone"
                    autocomplete="shopPhone"
                    maxlength="20"
                    placeholder="请输入账号"
                  /> -->
                </el-form-item>
                <el-form-item label="密码" prop="shopPassword">
                  <el-input
                    v-model="formData.shopPassword"
                    type="password"
                    maxlength="16"
                    autocomplete="shopPassword"
                    show-password
                    placeholder="请输入密码"
                    readonly
                    @focus="focusShopPhoneInput"
                  />
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商家配置" name="third">
                <div v-for="(group, i) in shopConfigList" :key="i" class="config-panel">
                  <div class="config-title">{{ group[0].configTypeDescribe }}</div>
                  <el-form-item
                    v-for="item in group"
                    :key="item.shopId + '-' + item.configModelId"
                    class="config-item"
                    :prop="item.configKey"
                    label-width="200px"
                    :rules="[{ required: item.hasDefault == 1, message: '请输入' + item.configText, trigger: 'blur' }]"
                  >
                    <!-- :label="item.configText" -->

                    <template #label>
                      <div class="config-item-label">{{ item.configText }}</div>
                    </template>
                    <div class="config-item-content">
                      <el-input
                        v-if="item.formType === 'el-input'"
                        v-model="item.configValue"
                        :type="(item.configValue || '').length > 30 ? 'textarea' : 'text'"
                        @change="(value) => onChange(value, item)"
                      />
                      <el-input-number
                        v-if="item.formType === 'el-input-number'"
                        v-model="item.configValue"
                        @change="(value) => onChange(value, item)"
                      />
                      <el-switch
                        v-else-if="item.formType === 'el-switch'"
                        v-model="item.configValue"
                        :inactive-value="item.options[0].value"
                        :active-value="item.options[1].value"
                        :inactive-text="item.options[0].label"
                        :active-text="item.options[1].label"
                        @change="(value) => onChange(value, item)"
                      />

                      <el-select
                        v-else-if="item.formType === 'el-select'"
                        v-model="item.configValue"
                        placeholder="请选择"
                        @change="(value) => onChange(value, item)"
                      >
                        <el-option
                          v-for="option in item.options"
                          :key="option?.value"
                          :label="option?.label"
                          :value="option?.value"
                          >{{ option?.label }}
                        </el-option>
                      </el-select>

                      <el-select
                        v-else-if="item.formType === 'el-select-multiple'"
                        v-model="item.configValue"
                        placeholder="请选择"
                        :multiple="true"
                        @change="(value) => onChange(value, item)"
                      >
                        <el-option
                          v-for="option in item.options"
                          :key="option?.value"
                          :label="option?.label"
                          :value="option?.value"
                          >{{ option?.label }}
                        </el-option>
                      </el-select>

                      <el-radio-group
                        v-else-if="item.formType === 'el-radio'"
                        v-model="item.configValue"
                        @change="(value) => onChange(value, item)"
                      >
                        <el-radio
                          v-for="option in item.options"
                          :key="option?.value"
                          :label="option?.label"
                          :value="option?.value"
                          >{{ option?.label }}
                        </el-radio>
                      </el-radio-group>

                      <el-checkbox-group
                        v-else-if="item.formType === 'el-checkbox'"
                        v-model="item.configValue"
                        @change="(value) => onChange(value, item)"
                      >
                        <el-checkbox
                          v-for="option in item.options"
                          :key="option?.value"
                          :label="option?.label"
                          :value="option?.value"
                          >{{ option?.label }}
                        </el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-form-item>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button v-if="activeName == 'third'" type="primary" :loading="submitLoading" @click="next(formRef)">
              确 定
            </el-button>
            <el-button v-else type="primary" @click="next">下一步</el-button>
          </span>
        </template>
      </el-dialog>
      <!--      商家域名-->
      <el-drawer v-model="draweShow" title="商家域名" direction="rtl" size="60%">
        <el-button style="margin-bottom: 10px" @click="addDomain">新建域名</el-button>
        <el-table
          v-loading="loadingDomain"
          :data="domainList"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          :style="{ width: '100%' }"
          class="dataTable"
        >
          <el-table-column label="域名" prop="domain" width="500px" />
          <el-table-column label="是否启用" prop="hasCurrent" width="100px">
            <template #default="{ row }">
              <div>{{ row.hasCurrent ? '是' : '否' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="hadnle">
            <template #default="{ row }">
              <el-button link type="primary" @click="editDomain(row)">编辑</el-button>
              <el-popconfirm title="确认删除？" @confirm="deleteDomain(row)">
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
      <!--      新建域名-->
      <el-dialog v-model="domainVisible" :align-center="true" :title="domainTypeData.title" width="40%" @close="close">
        <el-form ref="domainRef" :rules="domainRule" :model="domainForm" label-position="right" label-width="150px">
          <el-form-item label="店铺:">
            <el-input v-model="domainForm.name" disabled />
          </el-form-item>
          <el-form-item label="域名:" prop="domain">
            <el-input v-model.trim="domainForm.domain" :rows="4" resize="none" placeholder="请输入以URL">
              <template #prepend>
                <el-select v-model="selectUrl" style="width: 100px">
                  <el-option label="https://" value="1" />
                  <el-option label="http://" value="2" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否启用：">
            <el-radio-group v-model="domainForm.current">
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确认</el-button>
        </template>
      </el-dialog>

      <DialogRecharge ref="dialogRechargeRef" @ok="search" />
      <DialogRechargeLog ref="dialogRechargeLogRef" />
      <!--      批量更换域名-->
      <UpdateUrl ref="updateUrlRef" />
    </div>
  </div>
</template>

<script setup>
import { encrypt } from '@/utils/rsaEncrypt.js'
import { ref, onBeforeMount, nextTick, reactive, onMounted } from 'vue'
import moment from 'moment'
import {
  businessListGetAll,
  businessListSave,
  businessListGetById,
  businessListUpdate,
  businessListStart,
  delBusinessById,
  getDomainList,
  addDomainUrl,
  editDomainUrl,
  delDomainUrl,
  $getUrl,
} from '@/api/business'
import { postShopConfigModelGetAll, refreshBusinessDomain } from '@/api/shop'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import DialogRecharge from './dialogRecharge.vue'
import DialogRechargeLog from './dialogRechargeLog.vue'
import UpdateUrl from '@/views/business/businessList/updateUrl.vue'

// 商家域名弹框
const draweShow = ref(false)
const loadingDomain = ref(false)
// 域名列表
const domainList = ref([])
// 当前的商家信息
const currentBusiness = ref({
  shopId: 0,
  shopName: '',
  domain: '',
  hasCurrent: 0,
})
// 批量更换域名
const updateUrlRef = ref()
const handleUrl = () => (updateUrlRef.value.state.dialogVisible = true)
// 默认域名
const defaultUrl = ref('')
// 新建域名
const domainVisible = ref(false)
const selectUrl = ref('https://')
const domainTypeData = reactive({
  title: '',
  type: false,
})
const domainRef = ref()
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}
const disabledDateEnd = (time) => {
  return time.getTime() < Date.now()
}
const domainRule = {
  domain: [{ required: true, message: '请输入域名', trigger: 'blur' }],
}
const domainForm = reactive({
  shopId: '',
  domain: '',
  current: 1,
  domainId: '',
})
// 新建商家弹框
const formRef = ref(null)
const accountRef = ref(null)
const phoneRef = ref(null)
const detailsVisible = ref(false)
const dialogVisible = ref(false)
const activeName = ref('first')
const tableLoading = ref(false)
const detailLoading = ref(false)
const submitLoading = ref(false)
const searchData = ref({
  shopName: '', // 店铺名称
  shopCode: '', // 店铺编码
  chargePersonName: '', // 店铺负责人
  contractState: '', // 合同状态 1-有效 0-无效
  page: 1, // 当前页
  pageSize: 10, // 每页记录数
})
const formData = ref({
  shopName: '', // 店铺名称
  chargePersonName: '', // 店铺负责人
  chargePersonPhone: '', // 负责人电话
  shopAdress: '', // 地址
  effectiveDate: '', // 生效日期
  contractState: 1, // 合同状态 1-有效 0-无效
  auditLive: 1, // 直播间审核
  auditLiveProduct: 1, // 直播间商品审核
  shopPhone: '', // 账号
  shopPassword: '', // 密码
  doMain: '1', //  域名,
  expirationDate: '', // 失效日期
})
const rules = ref({
  doMain: [
    { required: true, message: '请输入店铺域名', trigger: 'blur' },
    {
      pattern: /^https?:\/\//,
      message: '请输入有效的域名',
      trigger: 'blur',
    },
  ],
  expirationDate: [
    { required: true, message: '请输入失效时限', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        console.log(111)
        if (!moment(value).isAfter(moment(formData.value.effectiveDate))) {
          callback(new Error('失效时间需大于生效时间'))
        } else {
          callback()
        }
        callback
      },
      trigger: 'blur',
    },
  ],
  shopName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
  chargePersonName: [{ required: true, message: '请输入店铺负责人', trigger: 'blur' }],
  chargePersonPhone: [
    { required: true, message: '请输入负责人电话', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '目前只支持中国大陆的手机号码',
    },
  ],
  shopAdress: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  contractState: [
    {
      required: true,
      message: '请选择合同状态',
      trigger: 'change',
    },
  ],
  auditLive: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'change',
    },
  ],
  auditLiveProduct: [
    {
      required: true,
      message: '请选择状态',
      trigger: 'change',
    },
  ],
  effectiveDate: [
    {
      required: true,
      message: '请选择日期',
      trigger: 'change',
    },
    {
      validator: (rule, value, callback) => {
        if (!moment(value).isBefore(moment(formData.value.expirationDate))) {
          callback(new Error('生效时间需早于失效时间'))
        } else {
          callback()
        }
        callback
      },
      trigger: 'blur',
    },
  ],
  shopPhone: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    // {
    //   pattern: /^1[3456789]\d{9}$/,
    //   message: '目前只支持中国大陆的手机号码'
    // }
  ],
  shopPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^[~!@#$%^&*\-+=_.0-9a-zA-Z]{8,16}$/,
      message: '8-16密码数字英文混合',
    },
  ],
})
const total = ref(1)
const tableData = ref([])
const userState = ref(1)
const privacyTime = ref(0)
const cpPhoneShow = ref(true) // 是否显示脱敏负责人手机号
const shopPhoneShow = ref(true) // 是否显示脱敏账号

onBeforeMount(() => {
  getAll(searchData.value)
  privacyTime.value = localStorage.getItem('privacyTime')
})
// 方法集合
const focusShopPhoneInput = (event) => {
  // shopPhoneShow.value = false
  // formData.value.shopPhone = ''
  // // 自动获取焦点
  // nextTick(() => {
  //   accountRef.value.focus()
  // })

  event.target.removeAttribute('readonly')
}
const focuscpPhoneInput = () => {
  cpPhoneShow.value = false
  formData.value.chargePersonPhone = ''
  // 自动获取焦点
  nextTick(() => {
    phoneRef.value.focus()
  })
}
// 分页
const handleSizeChange = (val) => {
  searchData.value.pageSize = val
  getAll(searchData.value)
}
const handleCurrentChange = (val) => {
  searchData.value.page = val
  getAll(searchData.value)
}
// 查询
const search = () => {
  getAll(searchData.value)
}
// 新建商家
const addbuss = () => {
  activeName.value = 'first' // 'second' 'third'
  userState.value = 0
  cpPhoneShow.value = false
  shopPhoneShow.value = false
  formData.value = {
    shopName: '', // 店铺名称
    chargePersonName: '', // 店铺负责人
    chargePersonPhone: '', // 负责人电话
    shopAdress: '', // 地址
    effectiveDate: '', // 生效日期
    expirationDate: '', // 失效日期
    contractState: 1, // 合同状态 1-有效 0-无效
    auditLive: 1,
    auditLiveProduct: 1,
    shopPhone: '', // 账号
    shopPassword: '', // 密码
    doMain: defaultUrl.value,
  }

  initShopConfigList()

  dialogVisible.value = true
}

const shopConfigList = ref([])

const updateConfigList = (list, isAdd) => {
  shopConfigList.value = []

  const configMap = list.reduce((acc, cur) => {
    if (isAdd) {
      cur.configModelId = cur.id
      cur.id = ''
    }
    if (!['el-input', 'el-input-number'].includes(cur.formType)) {
      cur.options = JSON.parse(cur.formValue)
      if (['el-select-multiple', 'el-checkbox'].includes(cur.formType)) {
        cur.configValue = (cur.configValue + '').split(',')
      } else if (typeof cur.options[0].value === 'number') {
        cur.configValue = +cur.configValue
      }
    }
    if (acc[cur.configType]) {
      acc[cur.configType].push(cur)
    } else {
      acc[cur.configType] = [cur]
    }

    formData.value[cur.configKey] = cur.configValue

    return acc
  }, {})

  for (const key in configMap) {
    shopConfigList.value.push(configMap[key])
  }
}
const initShopConfigList = () => {
  postShopConfigModelGetAll({
    page: 1,
    pageSize: 9999,
  }).then((res) => {
    if (res.data.list) {
      updateConfigList(res.data.list, true)
    }
  })
}

function onChange(value, item) {
  console.log('change', value, item)
  const configValue = ['el-select-multiple', 'el-checkbox'].includes(item.formType) ? value.toString() : value
  formData.value[item.configKey] = configValue
}

// 弹窗关闭
const onClosed = () => {
  cpPhoneShow.value = true
  shopPhoneShow.value = true
  formRef.value.resetFields()
}

const onValidateOk = () => {
  submitLoading.value = true
  // return console.log('formData: ', formData.value)
  if (!userState.value) {
    formData.value.shopConfigModel = shopConfigList.value.flat(2)
    console.log(formData.value)
    debugger
    businessListSave(formData.value)
      .then((res) => {
        if (res.code === '') {
          ElMessage({
            message: '新增成功',
            type: 'success',
          })
          getAll(searchData.value)
          dialogVisible.value = false
        }
      })
      .finally(() => {
        submitLoading.value = false
      })
  } else {
    formData.value.shopConfig = shopConfigList.value.flat(2)
    const tmpData = {}
    Object.assign(tmpData, formData.value)
    tmpData.shopPassword = encrypt(tmpData.shopPassword)
    businessListUpdate(tmpData)
      .then((res) => {
        if (res.code === '') {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          getAll(searchData.value)
          dialogVisible.value = false
        }
      })
      .finally(() => {
        submitLoading.value = false
      })
  }
}

const firstTabFields = [
  'shopName',
  'chargePersonName',
  'chargePersonPhone',
  'shopAdress',
  'effectiveDate',
  'expirationDate',
]
const secondTabFields = ['shopPhone', 'shopPassword']
// 下一步 or 提交
const next = () => {
  formRef.value.validate((valid, fields) => {
    if (valid) {
      if (activeName.value == 'first') {
        activeName.value = 'second'
      } else if (activeName.value == 'second') {
        activeName.value = 'third'
      } else {
        onValidateOk()
      }
    } else {
      const [key, value] = Object.entries(fields)[0] ?? {}
      const errorMessage = value[0]?.message ?? '请填写正确的信息'
      if (firstTabFields.includes(key)) {
        if (activeName.value != 'first') {
          activeName.value = 'first'
        }
        ElMessage.error(errorMessage)
      } else if (secondTabFields.includes(key)) {
        if (activeName.value != 'second') {
          activeName.value = 'second'
        }
        if (activeName.value == 'third') {
          ElMessage.error(errorMessage)
        }
      } else {
        activeName.value = 'third'
        ElMessage.error(errorMessage)
      }
    }
  })
}

// 查看
const seeMore = async (row) => {
  detailsVisible.value = true
  detailLoading.value = true
  try {
    const res = await businessListGetById({ shopId: row.shopId })
    if (res.code === '') {
      formData.value = res.data
      updateConfigList(res.data.shopConfig, false)
    }
  } finally {
    detailLoading.value = false
  }
}
// 编辑
const edit = async (row) => {
  activeName.value = 'first'
  userState.value = 1
  const res = await businessListGetById({ shopId: row.shopId })
  if (res.code === '') {
    formData.value = res.data
    console.log(formData.value.doMain)
    updateConfigList(res.data.shopConfig)
    dialogVisible.value = true
  }
}
// 停用/启动
const disableOrEnable = async (row) => {
  if (row.state === 1) {
    const res = await businessListStart({
      shopName: row.shopName,
      state: 0,
      shopId: row.shopId,
    })
    if (res.code === '') {
      ElMessage({
        message: '停用成功',
        type: 'success',
      })
      getAll(searchData.value)
    }
  } else {
    const res = await businessListStart({
      shopName: row.shopName,
      state: 1,
      shopId: row.shopId,
    })
    if (res.code === '') {
      ElMessage({
        message: '启用成功',
        type: 'success',
      })
      getAll(searchData.value)
    }
  }
}
// 删除
const delBusiness = (row) => {
  ElMessageBox.confirm('此操作将永久删除该商家, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      delBusinessById({
        shopId: row.shopId,
      }).then((res) => {
        if (res.code === '') {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getAll(searchData.value)
        }
      })
    })
    .catch(() => {})
}
// 初始化查询所有数据
const getAll = async (data) => {
  console.log('dada')
  tableLoading.value = true
  try {
    const res = await businessListGetAll(data)
    total.value = res.data.total
    tableData.value = res.data.list
  } finally {
    tableLoading.value = false
  }
}
// 中间部分
const hidden = (str, frontLen, endLen) => {
  let endLenData = 0
  if (str.length !== 2) {
    endLenData = endLen
  }
  const len = str.length - frontLen - endLenData
  let xing = ''
  for (let i = 0; i < len; i++) {
    xing += '*'
  }
  return str.substring(0, frontLen) + xing + str.substring(str.length - endLenData)
}
// 查看域名
const openDomain = async (data) => {
  draweShow.value = true
  Object.assign(currentBusiness.value, data)
  getDomain()
}
const getDomain = async () => {
  loadingDomain.value = true
  try {
    const res = await getDomainList({ shopId: currentBusiness.value.shopId })

    domainList.value = res.data
  } finally {
    loadingDomain.value = false
  }
}
// 编辑
const editDomain = async (data) => {
  domainForm.name = currentBusiness.value.shopName
  domainForm.shopId = data.shopId
  domainForm.domainId = data.domainId
  domainForm.domain = data.domain.split('//')[1]
  domainForm.current = data.hasCurrent
  console.log(domainForm.domain)
  domainTypeData.title = '编辑域名'
  domainVisible.value = true
  domainTypeData.type = true
}
// 新增域名
const addDomain = () => {
  domainVisible.value = true
  domainTypeData.title = '新建域名'
  domainTypeData.type = false
  domainForm.name = currentBusiness.value.shopName
  domainForm.shopId = currentBusiness.value.shopId
}
const close = () => {
  Object.keys(domainForm).forEach((key) => delete domainForm[key])
  domainForm.current = 1
  domainRef.value.resetFields()
  domainVisible.value = false
  selectUrl.value = 'https://'
}
const confirmAdd = () => {
  domainRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const data = {
        ...domainForm,
      }
      data.domain = `${selectUrl.value}${data.domain}`
      try {
        if (domainTypeData.type) {
          await editDomainUrl(data)
          ElMessage({ message: '修改成功', type: 'success' })
        } else {
          await addDomainUrl(data)
          ElMessage({ message: '新增成功', type: 'success' })
        }
        await getDomain()
        loading.close()
        close()
      } finally {
        loading.close()
      }
    }
  })
}
// 删除域名
const deleteDomain = (data) => {
  ElMessageBox.confirm('此操作将删除此域名吗, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await delDomainUrl({ domainId: data.domainId })
    if (res.code === '') {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getDomain()
    }
  })
}
// 获取默认域名
const getUrl = async () => {
  const res = await $getUrl({ dictName: 'DEFAULT_DOMAIN' })
  if (!res.code) {
    formData.value.doMain = res.data[0].dictValue
    defaultUrl.value = res.data[0].dictValue
    console.log('formData.value.doMain ==> ', formData.value.doMain)
  }
}
onMounted(getUrl)

const dialogRechargeRef = ref(null)
function openDialogRecharge(row) {
  console.log(row)
  dialogRechargeRef.value.show(row)
}

const dialogRechargeLogRef = ref(null)
function openDialogRechargeLog(row) {
  dialogRechargeLogRef.value.show(row)
}
// 刷新经销商域名
const flushed = (data) => {
  ElMessageBox.confirm(`确定要更新当前${data.shopName}店铺域名吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    formData.value = data
    const loading = ElLoading.service({
      background: 'rgba(0, 0, 0, 0.7)',
    })
    try {
      const res = await refreshBusinessDomain(formData.value)
      if (!res.code) {
        ElMessage({
          type: 'success',
          message: '刷新成功',
        })
        getAll(searchData.value)
      }
    } finally {
      loading.close()
    }
  })
}
</script>

<style lang="scss" scoped>
.pending {
  padding: 20px;
  margin-top: 20px;
  background-color: #ffffff;
}

.fenye {
  margin-top: 20px;
}

.elipt {
  width: 50%;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
.year {
  margin-left: 10px;
}

.config-panel {
  padding-left: 1em;
  .config-title {
    font-weight: bold;
    margin-bottom: 16px;
    margin-left: -1em;
  }
  .config-item-label {
    font-weight: normal;
    line-height: 1.1;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .config-item-content {
    width: 100%;

    .el-select {
      width: 100%;
    }
  }
}
:deep().el-input-group--prepend .el-input-group__prepend .el-select .el-select__wrapper {
  box-shadow: unset;
}
</style>
